//
//  CLdisgnerViewController.m
//  I-want-go
//
//  Created by dllo on 15/10/21.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "CLdisgnerViewController.h"
#import "BaseModel.h"
#import "CLdisgnerCollectionCell.h"
#import "CLdisgnerTableCell.h"
#import "CLdisgner.h"
#import "CLtool.h"
#import "CLdisgnerPic.h"
#import "CLproTableCell.h"
#import "CLinterViewController.h"
#import "CLpeopleViewController.h"
#import "CLscreen.h"
#import "CLSingleton.h"

@interface CLdisgnerViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate, CLproTableCellDelegate, CLdisgnerTableCellDelegate>

@property(nonatomic, retain)UICollectionView *myCollectionView;
@property(nonatomic, retain)UITableView *myTableView;
//@property(nonatomic, retain)NSString *strTitle;
@property(nonatomic, retain)NSArray *arrCollectionArr;
@property(nonatomic, retain)NSMutableArray *arr;
@property(nonatomic, assign)NSInteger page;
@property(nonatomic, retain)NSString *strID;
@end

@implementation CLdisgnerViewController
- (void)dealloc {
    [_strID release];
    [_arr release];
    [_arrCollectionArr release];
//    [_strTitle release];
    [_myTableView release];
    [_myCollectionView release];
    [super dealloc];
}

//- (void)iswlan {
//    
//    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
//    [manager startMonitoring];
//    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
//        if (status == 0) {
//            [CLSingleton shareSingleton].strState = NO;
//            self.tabBarController.tabBar.hidden = YES;
//            UIAlertController *aleryController = [UIAlertController alertControllerWithTitle:@"无连接" message:@"亲,连网再看" preferredStyle:UIAlertControllerStyleAlert];
//            [self presentViewController:aleryController animated:YES completion:nil];
//            UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//                UIImageView *dimage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 375 *SWIDTH, 667 * SHEIGHT)];
//                dimage.image = [UIImage imageNamed:@"go3.png"];
//                [self.view addSubview:dimage];
//                [dimage release];
//                UIAlertController *aleryController = [UIAlertController alertControllerWithTitle:@"无连接" message:@"亲,连网再看" preferredStyle:UIAlertControllerStyleAlert];
//                [self presentViewController:aleryController animated:YES completion:nil];
//                UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
//                [aleryController addAction:leftAction];
//            }];
//            [aleryController addAction:leftAction];
//        }
//        
//        else {
//            UIAlertController *aleryController = [UIAlertController alertControllerWithTitle:@"已连接" message:@"为wifi连接" preferredStyle:UIAlertControllerStyleAlert];
//            [self presentViewController:aleryController animated:YES completion:nil];
//            UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//                [self.myTableView reloadData];
//            }];
//            [aleryController addAction:leftAction];
//
//        }
//        
//    }];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    if ([CLSingleton shareSingleton] == NO) {
//        UIImageView *imgview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 375 *SWIDTH, 667 *SHEIGHT)];
//        imgview.image = [UIImage imageNamed:@"go3.png"];
//        [self.view addSubview:imgview];
//        [imgview release];
//    } else {
//    [self iswlan];
    self.view.backgroundColor = [UIColor grayColor];
   self.navigationController.navigationBar.translucent = NO;
    self.title = @"独立设计师";
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(115 * SWIDTH, 40 * SHEIGHT);

    self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 375 * SWIDTH, 50 * SHEIGHT) collectionViewLayout:flowLayout];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    [self.view addSubview:self.myCollectionView];
    self.myCollectionView.backgroundColor = [UIColor blackColor];
    [_myCollectionView release];
    [self.myCollectionView registerClass:[CLdisgnerCollectionCell class] forCellWithReuseIdentifier:@"reuse"];
    
    
    self.myCollectionView.dataSource = self;
    self.myCollectionView.delegate = self;
    
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50 * SHEIGHT, 375 * SWIDTH, 504 * SHEIGHT)];
    [self.view addSubview:self.myTableView];
    self.myTableView.rowHeight = 380 * SHEIGHT;
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_myTableView release];
    
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    
    [self create];
    
    self.myTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(header)];
    
    self.myTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerAction)];
//    }
}

- (void)header {
    self.page = 1;
    [self.arr removeAllObjects];
    [self create];
}


- (void)footerAction {
    
    self.page = 1;
    self.page++;
    
    NSLog(@"%@", self.strID);
    
    if ([self.strID  isEqualToString: @"2"] || [self.strID isEqualToString:@"3"]) {
        NSString *str = @"http://api.xiangqu.com/designerInfo/list";
        NSURL *url = [NSURL URLWithString:str];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
        NSString *bodyStr = [NSString stringWithFormat:@"key=10f0bd75af5d19089670446190e2d541&page=%ld&requestType=%@&sequenceType=1&t=1446082489042&userid=705811", (long)self.page, self.strID];
        NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:bodyData];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            
            NSMutableArray *linArr = [[NSMutableArray alloc] init];
            linArr = [CLdisgner baseModelByArr:dic[@"records"]];
            for (NSInteger i = 0; i < linArr.count; i++) {
                [linArr[i] setValue:[CLdisgnerPic baseModelByArr:[linArr[i] products]] forKey:@"products"];
            }
            
            for (CLdisgner *dis in linArr) {
                [self.arr addObject:dis];
            }
            [self.arr removeLastObject];
            [self.myTableView.footer endRefreshing];
            [self.myTableView reloadData];
        }];
    } else {
    NSString *str = @"http://api.xiangqu.com/designerInfo/list";
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = [NSString stringWithFormat:@"key=10f0bd75af5d19089670446190e2d541&page=%ld&requestType=1&sequenceType=1&t=1446082489042&userid=705811", (long)self.page];
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
       
                NSMutableArray *linArr = [[NSMutableArray alloc] init];
                linArr = [CLdisgner baseModelByArr:dic[@"records"]];
                for (NSInteger i = 0; i < linArr.count; i++) {
                    [linArr[i] setValue:[CLdisgnerPic baseModelByArr:[linArr[i] products]] forKey:@"products"];
                }
        
                for (CLdisgner *dis in linArr) {
                    [self.arr addObject:dis];
                }
        [self.arr removeLastObject];
        [self.myTableView.footer endRefreshing];
        [self.myTableView reloadData];
        
    }];
}
    
}
- (void)create {
    if ([self.strID isEqualToString:@"2"] || [self.strID isEqualToString:@"3"]) {
        NSString *str = @"http://api.xiangqu.com/designerInfo/list";
        NSURL *url = [NSURL URLWithString:str];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [request setHTTPMethod:@"POST"];
        NSString *bodyStr = [NSString stringWithFormat: @"key=10f0bd75af5d19089670446190e2d541&page=1&requestType=%@&sequenceType=1&t=1446082489042&userid=705811", self.strID];
        NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:bodyData];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            self.arr = [NSMutableArray array];
            self.arr = [CLdisgner baseModelByArr:dic[@"records"]];
            for (NSInteger i = 0; i < self.arr.count; i++) {
                [self.arr[i] setValue:[CLdisgnerPic baseModelByArr:[self.arr[i] products]] forKey:@"products"];
            }
            
            
            [self.myTableView.header endRefreshing];
            [self.myTableView reloadData];
            
        }];

    } else {
    NSString *str = @"http://api.xiangqu.com/designerInfo/list";
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = @"key=10f0bd75af5d19089670446190e2d541&page=1&requestType=1&sequenceType=1&t=1446082489042&userid=705811";
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        self.arr = [NSMutableArray array];
        self.arr = [CLdisgner baseModelByArr:dic[@"records"]];
        for (NSInteger i = 0; i < self.arr.count; i++) {
            [self.arr[i] setValue:[CLdisgnerPic baseModelByArr:[self.arr[i] products]] forKey:@"products"];
        }
        
        
        [self.myTableView.header endRefreshing];
        [self.myTableView reloadData];
        
    }];
    }
}

//////////tableView

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
        return self.arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CLdisgner *disgner = self.arr[indexPath.row];
    if ([disgner.isRecommend isEqualToString:@"1"]) {
        static NSString *reuse = @"reuse";
        CLdisgnerTableCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[CLdisgnerTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse];
        }
        
        cell.pushLabel.text = @"推荐";
        cell.titleLabel.text = disgner.designerName;
        [cell.phoneImage sd_setImageWithURL:[NSURL URLWithString:disgner.headPortrait]];
        cell.classifyLabel.text = disgner.designerTag;
        cell.likeLabel.text = @"相关作品";
        cell.funsLabel.text = [NSString stringWithFormat:@"作品:%@ / 粉丝:%@", disgner.productNum, disgner.fansNum];
        
        ///传数组
        cell.productArr = [self.arr[indexPath.row] products];
        [cell.picCollectionView reloadData];
        cell.tagArr = self.arr;
        // 协议
        cell.delegate = self;
        // 往图片上按tag
        cell.phoneImage.tag = indexPath.row;
        
        return cell;

    } else {
        static NSString *reuse = @"rae";
        CLproTableCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell = [[CLproTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse];
        }
        
        
        cell.pushLabel.text = disgner.designerLabel;
        cell.titleLabel.text = disgner.designerName;
        [cell.phoneImage sd_setImageWithURL:[NSURL URLWithString:disgner.headPortrait] placeholderImage:[UIImage imageNamed:@"good.png"]];
        cell.classifyLabel.text = disgner.designerTag;
        cell.likeLabel.text = @"相关作品";
        cell.funsLabel.text = [NSString stringWithFormat:@"作品:%@ / 粉丝:%@", disgner.productNum, disgner.fansNum];
        
        ///传数组
        
        cell.proArr = [self.arr[indexPath.row] products];
        [cell.picCollectionView reloadData];
        cell.bigArr = self.arr;
        
        cell.Delate = self;
        
        cell.phoneImage.tag = indexPath.row;
        return cell;

    }
    
}
// 跳转到设计者页//////
- (void)pushWithdisgnerId:(NSString *)disgnerId {
//    CLpeopleViewController *peVC = [[CLpeopleViewController alloc] init];
//    [self.navigationController pushViewController:peVC animated:YES];
    
//    peVC.strId = disgnerId;
//    NSLog(@"%@", peVC.strId);
}



// 跳到商品页///////////
- (void)pushWithId:(NSString *)pushId {
    
    CLinterViewController *intVC = [[CLinterViewController alloc] init];
    [self.navigationController pushViewController:intVC animated:YES];
    
    intVC.interId = pushId;
}

-(void)pushWithFirstId:(NSString *)firstId {
    CLinterViewController *intVC = [[CLinterViewController alloc] init];
    [self.navigationController pushViewController:intVC animated:YES];
    intVC.interId = firstId;
}

///////collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 3;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CLdisgnerCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];

    self.arrCollectionArr = @[@"独立设计师", @"手工匠人", @"达人买手"];
    cell.disegerLabel.text = self.arrCollectionArr[indexPath.row];
    cell.disegerLabel.textColor = [UIColor whiteColor];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    self.title = self.arrCollectionArr[indexPath.row];
    NSArray *arr= @[@"1", @"2", @"3"];
    
    NSString *strType = [NSString stringWithFormat:@"key=10f0bd75af5d19089670446190e2d541&page=1&requestType=%@&sequenceType=1&t=1446082489042&userid=705811", arr[indexPath.row]];
    NSString *str = @"http://api.xiangqu.com/designerInfo/list";
    NSURL *url = [NSURL URLWithString:str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = strType;
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        self.arr = [NSMutableArray array];
        self.arr = [CLdisgner baseModelByArr:dic[@"records"]];
        for (NSInteger i = 0; i < self.arr.count; i++) {
            [self.arr[i] setValue:[CLdisgnerPic baseModelByArr:[self.arr[i] products]] forKey:@"products"];
        }
        
        self.strID = arr[indexPath.row];
        [self.myTableView reloadData];
        
    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
